﻿using MiniExcelLibs;
using MobileControlGuru.Src;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace MobileControlGuru.AutoTask
{
    /// <summary>
    /// 引用源内容编辑
    /// </summary>
    public partial class CommentsForm : Form
    {

        public List<ReferenceSource> _referenceSources;
        public CommentsForm()
        {
            InitializeComponent();
        }
        public CommentsForm(List<ReferenceSource> referenceSources)
        {
            if (referenceSources != null)
            {
                _referenceSources = referenceSources;
            }
            InitializeComponent();
        }

        private void InitFlowPanel()
        {
            foreach (var item in _referenceSources)
            {
                var commentitem = new CommentControl(item);
                commentitem.deleteCommentEevnt += ItemDelete;

                this.flowLayoutPanel1.Controls.Add(commentitem);

            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            var edit = new CommentControl();
            edit.deleteCommentEevnt += ItemDelete;
            
            this.flowLayoutPanel1.Controls.Add(edit);
            UpdateItemIndex();
        }
        public void ItemDelete(int index)
        {
            UpdateItemIndex();
        }
        private void UpdateItemIndex()
        {
            int i = 0;
            foreach (CommentControl c in this.flowLayoutPanel1.Controls)
            {
                c.SetIndex(++i);
            }
        }

        public List<ReferenceSource> GetSources()
        {
            List<ReferenceSource> sources = new List<ReferenceSource>();
            foreach (CommentControl item in this.flowLayoutPanel1.Controls)
            {
                ReferenceSource referenceSource = new ReferenceSource();
                referenceSource.RContent = item.inputComment.Text;
                sources.Add(referenceSource);
            }
            return sources;
        }
        private void buttonClear_Click(object sender, EventArgs e)
        {
            _referenceSources = null;
            this.flowLayoutPanel1.Controls.Clear();
        }

        private void CommentsForm_Load(object sender, EventArgs e)
        {
            if (_referenceSources != null)
            {
                InitFlowPanel();
            }
        }

        private void buttonImport_Click(object sender, EventArgs e)
        {
            // 使用OpenFileDialog让用户选择JSON文件
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "JSON files (*.json)|*.json",
                DefaultExt = "json"
            };

            // 如果用户选择了文件并点击了“打开”
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 读取JSON文件的内容
                    string jsonFilePath = openFileDialog.FileName;
                    string jsonData = File.ReadAllText(jsonFilePath);

                    // 反序列化JSON字符串到对象列表
                    List<ReferenceSource> dataList = JsonConvert.DeserializeObject<List<ReferenceSource>>(jsonData);

                    // 使用dataList中的数据
                    // 例如，将其显示在DataGridView或其他控件中
                    _referenceSources = dataList;
                    this.InitFlowPanel();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导入失败：{ex.Message}");
                }
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            List<ReferenceSource> list = GetSources();

            // 序列化数据到JSON字符串
            string jsonData = JsonConvert.SerializeObject(list, Formatting.Indented);
            // 创建SaveFileDialog实例并配置
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "JSON (*.json)|*.json|所有文件 (*.*)|*.*";
            saveFileDialog.Title = "外部数据源";
            saveFileDialog.FileName = $"外部数据源_{DateTime.Now.ToString("yyyyMMddHHmmss")}"; // 默认文件名

            // 显示保存对话框并获取用户选择
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {


                try
                {
                    File.WriteAllText(saveFileDialog.FileName, jsonData);

                    MessageBox.Show("数据导出成功！");
                }
                catch (Exception ex)
                {
                    // 处理文件写入过程中的异常
                    MessageBox.Show($"导出失败：{ex.Message}");
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void buttonImportExcel_Click(object sender, EventArgs e)
        {
            // 使用OpenFileDialog让用户选择JSON文件
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Excel files (*.json)|*.xlsx",
                DefaultExt = "xlsx"
            };

            // 如果用户选择了文件并点击了“打开”
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // 读取JSON文件的内容
                    string jsonFilePath = openFileDialog.FileName;
                    //string jsonData = File.ReadAllText(jsonFilePath);

                    // 反序列化JSON字符串到对象列表
                    //List<ReferenceSource> dataList = JsonConvert.DeserializeObject<List<ReferenceSource>>(jsonData);
                    var rows = MiniExcel.Query(jsonFilePath).ToList();
                    List<ReferenceSource> dataList = new List<ReferenceSource>();
                    for (int i = 1; i < rows.Count; i++)//跳过首行
                    {
                        ReferenceSource operateParam = new ReferenceSource()
                        {
                            RContent = DynamicStringHelper.DynamicToString(rows[i].A),
                             
                        };

                        dataList.Add(operateParam);
                        Console.WriteLine($"RContent: {rows[i].A}");
                    }
                    // 使用dataList中的数据
                    // 例如，将其显示在DataGridView或其他控件中
                    _referenceSources = dataList;
                    this.InitFlowPanel();
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导入失败：{ex.Message}");
                }
            }
        }

        private void buttonExportExcel_Click(object sender, EventArgs e)
        {
            List<ReferenceSource> list = GetSources();

            // 序列化数据到JSON字符串
            //string jsonData = JsonConvert.SerializeObject(list, Formatting.Indented);
            // 创建SaveFileDialog实例并配置
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "xlsx (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*";
            saveFileDialog.Title = "外部数据源";
            saveFileDialog.FileName = $"外部数据源_{DateTime.Now.ToString("yyyyMMddHHmmss")}"; // 默认文件名

            // 显示保存对话框并获取用户选择
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {


                try
                {
                    //File.WriteAllText(saveFileDialog.FileName, jsonData);
                    var values = new List<Dictionary<string, object>>();
                    foreach (var item in list)
                    {
                        var dic = new Dictionary<string, object> { { "RContent", item.RContent } };
                        values.Add(dic);

                    }
                    //File.WriteAllText(saveFileDialog.FileName, jsonData);
                    MiniExcel.SaveAs(saveFileDialog.FileName, values);
                   
                    MessageBox.Show("数据导出成功！");
                }
                catch (Exception ex)
                {
                    // 处理文件写入过程中的异常
                    MessageBox.Show($"导出失败：{ex.Message}");
                }
            }
        }
    }
}
